//插件文档: https://ext.dcloud.net.cn/plugin?id=392
import Request from "./request.js";
const instance = new Request();

let globalConfig = {
  // #ifdef APP-PLUS || MP-WEIXIN || H5
 // baseUrl: "https://daily.fangliyun.com/prod-api",
 //baseUrl: "http://180.76.118.64:2222/prod-api",
 //baseUrl: "http://dny.xiandimingzhi.com/prod-api",
 baseUrl: "http://www.xian-map.com/prod-api",
 
  // #endif
  header: {
    "Content-Type": "application/json; charset=utf-8",
  },
};

function setToken(e) {
  uni.setStorageSync("token", e);
}

function getToken() {
  return uni.getStorageSync("token");
}

instance.setConfig((config) => {
  /* 设置全局配置 */
  config.baseUrl = globalConfig.baseUrl;
  config.header = {
    ...config.header,
    ...globalConfig.header,
  };
  return config;
});

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
instance.validateStatus = (statusCode) => {
  return statusCode === 200;
};

instance.interceptor.request((config, cancel) => {
  /* 请求之前拦截器 */
  let header = config.custom.header || {};
  // let token = getToken();
  // if (!token && !requestUrlWithoutToken.indexOf(config.url)) {
  //     uni.navigateTo({
  //         url: '/pages/login/login'
  //     });
  // }
  config.header = {
    ...config.header,
    ...header,
    // Authorization: token,
  };
  return config;
});

instance.interceptor.response(
  (response) => {
    /* 请求之后拦截器 */
    if (response.data.code === "000015") {
      uni.navigateTo({
        url: "/pages/login/index",
      });
      return Promise.reject(response);
    }
    if (response.data.code != 200) {
      // return Promise.reject(response)
      let result = {
        code: response.data.code,
        message: response.data.msg,
        data: response.data.data,
      };
      uni.hideToast();
      uni.showToast({
        title:'加载失败',// result.message,
        icon: "none",
        duration: 3000,
      });
      return result;
    }
    return response.data;
  },
  (response) => {
    // 请求错误做点什么
    uni.showToast({
      title:'连接超时', //JSON.stringify(response),
      icon: "none",
      duration: 10000,
    });
    switch (response.statusCode) {
      case 500:
        uni.showToast({
          title: '服务器连接失败',// response.data.msg,
          icon: "none",
        });
        break;
      case 401:
        uni.navigateTo({
          url: "/pages/login/index",
        });
        break;
      default:
        break;
    }
    // let result = new Object()
    // result.code = '999999';
    // result.msg = "请检查网络"
    // uni.showToast({
    //     title: result.msg,
    //     icon: 'none'
    // });
    // return result;
    return response;
  }
);

function send(method, url, data = {}, params = {}, custom = {}) {
  let prom = instance.request({
    method: method.toUpperCase(), // 请求方法必须大写
    url,
    data,
    // params会拼接到url上
    params,
    // 可以加一些自定义参数，在拦截器等地方使用
    custom,
  });
  return prom;
}
// function download(method, url, data = {}, params = {}) {
// 	let prom = instance.request({
// 		method: method.toUpperCase(), // 请求方法必须大写
// 		url,
// 		data,
// 		// params会拼接到url上
// 		params,
// 		// 可以加一些自定义参数，在拦截器等地方使用
// 		responseType:'Blob'
// 	})

// 	return prom;

// }
// 具体文档参照uni的上传下载 https://uniapp.dcloud.io/api/request/network-file
// 直接发起一个 multipart/form-data 的 post请求
function upload(url, filePath, otherFormData = {}, complete = (res) => {}) {
  //在这里可以获取token塞进header
  let header = {
    Authorization: getToken(),
  };

  let uploadTask = uni.uploadFile({
    url: `${globalConfig.baseUrl}${url}`,
    filePath,
    name: "file",
    header: {
      ...globalConfig.header,
      ...header,
    },
    formData: otherFormData,
    complete,
  });
  // uploadTask.abort(); 中断上传
  // uploadTask.onProgressUpdate(callback); 监听进度

  return uploadTask;
}

// 具体文档参照uni的上传下载 https://uniapp.dcloud.io/api/request/network-file
// 直接发起一个get请求
function download(url, complete = (res) => {}) {
  //在这里可以获取token塞进header
  let header = {
    Authorization: "Bearer " + getToken(),
    // responseType: 'blob'
  };

  let downloadTask = uni.downloadFile({
    url: `${globalConfig.baseUrl}${url}`,
    header: {
      ...globalConfig.header,
      ...header,
    },
    complete,
  });

  // downloadTask.abort(); 中断下载
  // downloadTask.onProgressUpdate(callback); 监听进度

  return downloadTask;
}

export default {
  send,
  upload,
  download,
  setToken,
  getToken,
  globalConfig,
};
